<?php

namespace App\Models;


use Illuminate\Support\Facades\DB;

class ArticleView extends Base
{

    // 文章浏览记录（一般只有添加操作）
    protected $table = 'article_view';

    // 缓存字段，用于搜索的字段
    protected $cacheFields = ['id', 'uid', 'article_id', 'channel', 'channel',];

    // 浏览记录
    public function addView($uid, $article_id, $ip, $channel = 'article', $terminal = '')
    {
        $model    = new News();
        $channels = $model->channels(true);
        if(!in_array($channel, $channels)){
            return $this->return_false("错误的操作频道!");
        }
        if(empty($uid)){
            return true;
        }

        // 浏览记录是否存在
        $self  = ['uid' => $uid, 'article_id' => $article_id, 'channel' => $channel, 'terminal' => $terminal,];
        $vImfo = $this->isCache(true)->oneFind($self);
        if(!empty($vImfo)){
            return true;
        }

        $topicWhere  = [];
        $userModifDb = new UserModify();
        // article: read_no  virtual_no
        // article_addon:  read_no  read_pc  virtual_pc
        $topicDb = new Topic();
        $userDb  = new User();
        $windDb  = new Wind();
        $wTagDb  = new WindTag();
        $number  = mt_rand(5, 10);
        $nwDb    = new NewsWind();
        $ntDb    = new NewsWindTag();
        $atDb    = new NewsTopic();
        $addDb   = new NewsAddon();
        $dateDb  = new NewsDate();
        $day     = date('Ymd');
        // 记录是否存在
        $windWhere  = ['news_id' => $article_id];
        $tagWhere   = ['news_id' => $article_id];
        $topicWhere = ['news_id' => $article_id];
        $dateWhere  = ['news_id' => $article_id, 'day' => $day];
        $dateInfo   = $dateDb->isCache(true)->oneFind($dateWhere);

        // 浏览记录
        $view = ['uid' => $uid, 'article_id' => $article_id, 'ip' => $ip, 'channel' => $channel, 'terminal' => $terminal, 'ctime' => LARAVEL_TIME, 'mtime' => LARAVEL_TIME];

        // 查找话题（如果内容有关联的话题表）
        $topicIds = [];
        if($atDb && $topicWhere){
            $topicIds = $atDb->isCache(true)->getList($topicWhere);
            $topicIds = is_object($topicIds) ? $topicIds->toArray() : $topicIds;
            $topicIds = array_column($topicIds, 'topic_id');
        }

        // 风向标
        $windIds = [];
        if($nwDb && $windWhere){
            $windIds = $nwDb->isCache(true)->getList($windWhere);
            $windIds = is_object($windIds) ? $windIds->toArray() : $windIds;
            $windIds = array_column($windIds, 'wind_id');
        }
        // 风向标的标签
        $tagIds = [];
        if($ntDb && $tagWhere){
            $tagIds = $ntDb->isCache(true)->getList($tagWhere);
            $tagIds = is_object($tagIds) ? $tagIds->toArray() : $tagIds;
            $tagIds = array_column($tagIds, 'tag_id');
        }

        //更新访问信息
        /*$addon   = [
            "read_no"            => DB::raw("read_no+1"),
            "read_".$terminal    => DB::raw("read_".$terminal."+1"),
            "virtual_".$terminal => DB::raw("virtual_".$terminal."+".$number),
        ];*/
        $uData   = ['view_no' => DB::raw("view_no+1")];
        $updata  = [
            "read_no"    => DB::raw("read_no+1"),
            "virtual_no" => DB::raw("virtual_no+".$number),
        ];
        $upCache = [
            "read_no"    => "+1",
            "virtual_no" => "+$number",
        ];
        // 如果是要闻（每一天都有访问记录）
        //if($channel == 'news'){}
        $upDateData  = ["read_no" => DB::raw("read_no+1"), "virtual_no" => DB::raw("virtual_no+".$number), "read_".$terminal => DB::raw("read_".$terminal."+1"), "virtual_".$terminal => DB::raw("virtual_".$terminal."+".$number),];
        $upDateCache = ["news_id" => $article_id, "read_no" => "+1", "virtual_no" => "+$number", "read_".$terminal => "+1", "virtual_".$terminal => "+$number",];
        if(empty($dateInfo)){
            $dateData = ['news_id' => $article_id, 'date' => $day, 'day' => $day, 'month' => date('Ym'), 'read_no' => 1, 'virtual_no' => $number, 'read_'.$terminal => 1, 'virtual_'.$terminal => $number];
        } else{
            $dateData = $upDateData;
        }


        // 执行操作
        $where2 = ["id" => $article_id];  // 条件
        DB::beginTransaction();
        try{
            // 增加访问量
            $model->where($where2)->update($updata);

            // 浏览记录
            self::insert($view);

            // 增加用户的访问量
            $userModifDb->where('uid', $uid)->update($uData);

            // 新闻：每天的浏览统计
            //if($channel == 'news'){}
            $addDb->where('news_id', $article_id)->update($upDateData);
            if($dateInfo){
                $dateDb->where('id', $dateInfo['id'])->update($dateData);
            } else{
                $dateDb->insert($dateData);
            }

            // 增加话题访问数量
            if($topicIds){
                foreach($topicIds as $topicId){
                    $topicDb->where('id', $topicId)->update($updata);
                }
            }

            // 增加风向标访问数量
            if($windIds){
                foreach($windIds as $_wid){
                    $windDb->where('id', $_wid)->update($updata);
                }
            }

            // 增加风向标的标签访问数量
            if($tagIds){
                foreach($tagIds as $tId){
                    $wTagDb->where('id', $tId)->update($updata);
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($self);
        // 文章详情 重新缓存
        /*if($view){
            $userDb->reSaveCache($uid, ['view_no' => '+1']);
        }*/
        /*if($topicIds){
            foreach($topicIds as $topicId){
                $topicDb->reSaveCache($topicId, $upCache);
            }
        }*/
        $model->reSaveCache($article_id, $upCache);
        $userDb->deleteCacheShow(['id' => $uid]);
        if($channel == 'news'){
            $dateDb->deleteCacheShow($dateInfo, $upDateCache);
            $addDb->deleteCacheShow($upDateCache);
        }
        $topicDb->deleteCacheShow(['id' => $topicIds]);
        $windDb->deleteCacheShow(['id' => $windIds]);
        $wTagDb->deleteCacheShow(['id' => $tagIds]);


        return true;
    }

    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            'uid'        => 'required|numeric',
            'article_id' => 'required|numeric',
            'channel'    => 'required',
            'ip'         => 'required',
        ];


        $msg = [
            'id'         => '自编号',
            'channel'    => 'article:文章 comment：评论，news：新闻，fresh：长短文',
            'uid'        => '用户ID',
            'article_id' => '文章ID',
            'ip'         => '用户IP',
            'ctime'      => '浏览时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }
}
